/*
* autoupdate.cpp - This file is the part of the wp-notifier.(code name "luan luan")
* Copyright (C) 2010 Dean Lee <deanlee3@gmail.com>, http://www.deanlee.cn
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
* 
* Acknowledgements:
*   <> Many thanks to all of you, who have encouraged me to update my articles
*     and code, and who sent in bug reports and fixes.
* 
*/
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QUrl>
#include <QNetworkRequest>
#include <QPushButton>
#include <QLabel>
#include <QGridLayout>
#include "common.h"
#include "autoupdate.h"


NewVersionDlg::NewVersionDlg(const QString& msg, QWidget* parent) : QDialog(parent)
{
	setAttribute(Qt::WA_DeleteOnClose);
	setModal(false);
	QGridLayout* vbox = new QGridLayout(this);
	QLabel *lb = new QLabel(this);
	vbox->addWidget(lb, 0, 0);
	lb->setTextFormat(Qt::RichText);
	lb->setText(msg);
	lb->setOpenExternalLinks(true);
	QPushButton* btn = new QPushButton(this);
	btn->setText(tr("Ok"));
	connect(btn, SIGNAL(clicked()), SLOT(accept()));
	vbox->addWidget(btn, 1, 0, Qt::AlignCenter);
	show();
}

NewVersionDlg::~NewVersionDlg()
{
}

AutoUpdate::AutoUpdate(QObject* parent) : QObject(parent)
{
	m_manager = new QNetworkAccessManager(this);
	connect(m_manager, SIGNAL(finished(QNetworkReply*)),this, SLOT(replyFinished(QNetworkReply*)));
	m_manager->get(QNetworkRequest(QUrl(CHECK_VERSION_URL)));
}

AutoUpdate::~AutoUpdate()
{
}

void AutoUpdate::replyFinished(QNetworkReply* reply)
{
	if (reply->error() == QNetworkReply::NoError) {
		QByteArray data = reply->readAll();
		QString version = data;
		if (version != QString(PROG_VERSION)) {
			emit updateAvailable(version);
			
		}
	}
	deleteLater();
}